package org.zjsru.order.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjsru.order.mapper.OrderMapper;
import org.zjsru.order.pojo.Order;
import org.zjsru.order.service.OrderService;
import org.zjsru.order.service.ProductFeignClient;
import org.zjsru.order.service.UserServiceFeign;
import org.zjsru.order.pojo.Product;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.Map;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public Order queryOrderById(Long orderId) {
        Order order = orderMapper.findById(orderId);
        if (order != null) {
            // 查询用户信息
            order.setUser(userServiceFeign.findById(order.getUserId()));
        }
        return order;
    }

    @Override
    @Transactional
    public Order createOrder(Order order) {
        // 1. 验证用户有效性
        Map<String, Object> userStatusResult = userServiceFeign.checkUserStatus(order.getUserId());
        Object statusObj = userStatusResult.get("status");
        boolean status = false;
        if (statusObj instanceof Boolean) {
            status = (Boolean) statusObj;
        } else if (statusObj instanceof String) {
            status = Boolean.parseBoolean((String) statusObj);
        }
        if (!status) {
            throw new RuntimeException("用户状态异常");
        }

        // 2. 获取商品信息
        Product product = productFeignClient.getProductById(order.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 3. 设置商品信息
        order.setProductName(product.getName());
        order.setPrice(product.getPrice());

        // 4. 生成订单号
        order.setOrderNo(generateOrderNo());
        order.setStatus(0); // 待支付状态
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        // 5. 计算总金额
        order.setTotalAmount(order.getPrice().multiply(new BigDecimal(order.getQuantity())));

        // 6. 保存订单
        orderMapper.insert(order);

        // 7. 调用商品服务扣减库存
        boolean stockResult = productFeignClient.decreaseStock(order.getProductId(), order.getQuantity());
        if (!stockResult) {
            throw new RuntimeException("库存不足");
        }

        log.info("订单创建成功，订单号: {}", order.getOrderNo());
        return order;
    }

    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        return orderMapper.findByUserId(userId);
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(Long orderId, Integer status) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);
        order.setUpdateTime(LocalDateTime.now());
        
        if (status == 1) { // 已支付
            order.setPayTime(LocalDateTime.now());
        }
        
        int result = orderMapper.update(order);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean cancelOrder(Long orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            return false;
        }

        // 更新订单状态为已取消
        boolean result = updateOrderStatus(orderId, 2);
        
        if (result) {
            // 恢复库存
            productFeignClient.increaseStock(order.getProductId(), order.getQuantity());
            log.info("订单已取消，订单号: {}", order.getOrderNo());
        }
        
        return result;
    }

    @Override
    @Transactional
    public void handleOrderTimeout(Long orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null || order.getStatus() != 0) {
            return;
        }

        // 更新订单状态为已超时
        updateOrderStatus(orderId, 3);
        
        // 恢复库存
        productFeignClient.increaseStock(order.getProductId(), order.getQuantity());
        
        log.info("订单已超时，订单号: {}", order.getOrderNo());
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "ORDER" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }
} 